import HandleBtn from '@/components/HandleBar/btn';
import {
  ModalForm,
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker,
  ProFormDigit,
  ProFormGroup,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTimePicker,
  ProTable,
} from '@/components/Pro/';
import {
  strategyControllerImplShowTimedStrategy,
  strategySchemeControllerImplAddTimeScheme,
  strategySchemeControllerImplDeleteTimeScheme,
  strategySchemeControllerImplListTimeScheme,
  strategySchemeControllerImplUpdateTimeScheme,
} from '@/services/ess/strategy';
import { EditOutlined } from '@ant-design/icons';
import {
  ConfigProvider,
  message,
  Modal,
  Popconfirm,
  RadioChangeEvent,
  Space,
  Tabs,
  Tag,
} from 'antd';
import { CheckboxChangeEvent } from 'antd/es/checkbox';
import dayjs from 'dayjs';
import React, { ForwardedRef, forwardRef, useCallback, useEffect, useRef, useState } from 'react';
import { useIntl } from 'umi';
import styles from '../index.less';
import {
  GroupedStrategy,
  TimeCtrl,
  TimeScheme,
  TimeSettingsProps,
  WeekStrategy,
} from '../types/timeStrategy';

import {
  calculateMiddleDay,
  getCtrlType,
  getNextMonthFirstDay,
  getPeakValleyType,
  sortDateStrategies,
  timeCtrlToFormValues,
  validateStrategyName,
} from './utils';

import {
  getChargeTypeOptions,
  getExecutionModeOptions,
  getMonthTagsData,
  getStrategyNameRules,
  getTimeTypeOptions,
  getWeekTagsData,
} from './TimeSettings/constant';

const TimeSettings = forwardRef(
  (
    { readOnly = false, currentAreaId, strategyData }: TimeSettingsProps,
    ref: ForwardedRef<any>,
  ) => {
    const [activeStrategyTab, setActiveStrategyTab] = useState<number | null>();
    const intl = useIntl();
    const isEnglish = intl.locale === 'en-US';
    const [executionMode, setExecutionMode] = useState<'date' | 'week'>('date');
    const tagsData = getMonthTagsData(intl);
    const weekTagsData = getWeekTagsData(intl);
    const [selectedMonths, setSelectedMonths] = useState<string[]>([]);
    const [selectedWeek, setSelectedWeek] = useState<string[]>([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [currentMonth, setCurrentMonth] = useState<string>('');
    // const [strategies, setStrategies] = useState<Strategy[]>([]);
    const [addStrategyModalVisible, setAddStrategyModalVisible] = useState(false);
    const [strategyItems, setStrategyItems] = useState<
      Array<{ key: string; label: string; children: React.ReactNode }>
    >([]);
    const [addTimeSlotModalVisible, setAddTimeSlotModalVisible] = useState(false);

    // 新状存储接口返回的数据
    const [, setStrategyData] = useState<any>(null);
    const [weekStrategyList, setWeekStrategyList] = useState<WeekStrategy[]>([]);
    const [currentEditingWeekIndex, setCurrentEditingWeekIndex] = useState<number | null>(null);

    // 新增状态存储时间策略方案
    const [timeSchemes, setTimeSchemes] = useState<TimeScheme[]>([]);
    const [tempSchemes, setTempSchemes] = useState<TimeScheme[]>([]);

    // 添加日期策略列表状态
    // const [dateStrategyList, setDateStrategyList] = useState<DateStrategy[]>([]);

    // 添加组策略的状态
    const [groupedStrategies, setGroupedStrategies] = useState<GroupedStrategy>({});

    // 添加新状态用于管理选中的策略
    const [selectedStrategyKeys, setSelectedStrategyKeys] = useState<string[]>([]);
    // 加状态用于当前月份的策略列表
    const [currentMonthStrategies, setCurrentMonthStrategies] = useState<any[]>([]);

    // 添加新的状态
    const [editingTimeCtrl, setEditingTimeCtrl] = useState<TimeCtrl | null>(null);
    const [isEditMode, setIsEditMode] = useState(false);
    // 1. 使用 useRef 来保存最新的 tempSchemes
    const tempSchemesRef = useRef<TimeScheme[]>([]);

    // 声明一个 form 实例
    const [form] = ProForm.useForm();

    // 2. 修改 setTempSchemes
    const updateTempSchemes = (schemes: TimeScheme[]) => {
      tempSchemesRef.current = schemes;
      setTempSchemes(schemes);
    };

    const handleTagChange = (tag: string, checked: boolean) => {
      if (executionMode === 'date') {
        setCurrentMonth(tag);
        const monthIndex = tagsData.indexOf(tag) + 1;
        let strategies = groupedStrategies[monthIndex] || [];

        // 如果策略为空，创建默认策略
        if (strategies.length === 0) {
          const nextMonthFirst = getNextMonthFirstDay(monthIndex);
          strategies = [
            {
              month: monthIndex,
              day: 1,
              timeSchemeSn: null,
              isNew: true,
            },
            {
              month: nextMonthFirst.month,
              day: nextMonthFirst.day,
              timeSchemeSn: null,
              isLastDay: true,
            },
          ];
        }

        setCurrentMonthStrategies(strategies);
        setModalVisible(true);
        return;
      }

      const weekIndex = weekTagsData.indexOf(tag);
      console.log('Week tag clicked:', { tag, checked, weekIndex });

      // 周模式下，直接打开编辑弹窗
      setCurrentEditingWeekIndex(weekIndex);
      setModalVisible(true);
    };

    // const handleAddStrategy = () => {
    //   setStrategies((prevStrategies) => [
    //     ...prevStrategies,
    //     { id: Date.now(), name: 'New Strategy' },
    //   ]);
    // };

    // 1. 先定义一个创建列配置的函数
    const createColumns = (
      handlers: {
        onEdit?: (record: any) => void;
        onDelete?: (timeKey: string) => void;
      } = {},
    ) => {
      const baseColumns = [
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.id' }),
          dataIndex: 'id',
          valueType: 'index',
          width: 60,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.startTime' }),
          dataIndex: 'startTime',
          width: 100,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.endTime' }),
          dataIndex: 'endTime',
          width: 100,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.chargeType' }),
          dataIndex: 'chargeType',
          width: 100,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.timeType' }),
          dataIndex: 'timeType',
          width: 80,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.SOCLower' }),
          dataIndex: 'socLower',
          width: 100,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.SOCUpper' }),
          dataIndex: 'socUpper',
          width: 100,
        },
        {
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.targetPower' }),
          dataIndex: 'targetPower',
          width: 120,
        },
      ];

      if (!readOnly) {
        baseColumns.push({
          title: intl.formatMessage({ id: 'strategyAction.baseColumns.operation' }),
          dataIndex: 'operation',
          width: 120,
          render: (_, record) => (
            <Space>
              <a onClick={() => handlers.onEdit?.(record)}>
                {intl.formatMessage({ id: 'strategyAction.baseColumns.edit' })}
              </a>
              <Popconfirm
                title={intl.formatMessage({ id: 'strategyAction.baseColumns.confirmDelete' })}
                description={intl.formatMessage({
                  id: 'strategyAction.baseColumns.pleaseBeCautious',
                })}
                onConfirm={() => handlers.onDelete?.(record.timeKey)}
                okText={intl.formatMessage({ id: 'strategyAction.baseColumns.confirm' })}
                cancelText={intl.formatMessage({ id: 'strategyAction.baseColumns.cancel' })}
              >
                <a style={{ color: 'red' }}>
                  {intl.formatMessage({ id: 'strategyAction.baseColumns.delete' })}
                </a>
              </Popconfirm>
            </Space>
          ),
        });
      }

      return baseColumns;
    };

    // 修改编辑处理函数
    const handleEditTimeSlot = (record: any) => {
      console.log('Edit Record:', record);

      const currentScheme = tempSchemesRef.current.find(
        (scheme) => scheme.id === activeStrategyTab,
      );

      if (!currentScheme) {
        message.error(intl.formatMessage({ id: 'strategyAction.error.pleaseSelectStrategyPlan' }));
        return;
      }

      const timeCtrl = currentScheme.timeCtrls.find((ctrl) => ctrl.timeKey === record.timeKey);

      if (!timeCtrl) {
        message.error(intl.formatMessage({ id: 'strategyAction.error.noTimeSlotData' }));
        return;
      }

      // 转换数据为表单值
      const formValues = timeCtrlToFormValues(intl, timeCtrl);

      // 设置编辑状态
      setEditingTimeCtrl({
        ...timeCtrl,
        originalTimeKey: timeCtrl.timeKey, // 保存原始的 timeKey
      });

      // 设置表单值
      form.setFieldsValue(formValues);

      setIsEditMode(true);
      setAddTimeSlotModalVisible(true);
    };

    // 4. 更新表格显示逻辑
    const updateStrategyTableDisplay = (
      currentSchemes: TimeScheme[],
      activeSchemeId: number | null,
      currentItems: typeof strategyItems,
    ) => {
      return currentItems.map((item) => {
        if (item.key === String(activeSchemeId)) {
          const currentScheme = currentSchemes.find((scheme) => scheme.id === activeSchemeId);

          // 对时间控制进行排序
          const sortedTimeCtrls = currentScheme?.timeCtrls.sort((a, b) => {
            const timeA = `${String(a.hour).padStart(2, '0')}:${String(a.minute).padStart(
              2,
              '0',
            )}:${String(a.second).padStart(2, '0')}`;
            const timeB = `${String(b.hour).padStart(2, '0')}:${String(b.minute).padStart(
              2,
              '0',
            )}:${String(b.second).padStart(2, '0')}`;
            return timeA.localeCompare(timeB);
          });

          const tableData = sortedTimeCtrls?.map((ctrl, index) => {
            // 计算结束时间
            let endTime = '24:00:00';
            if (index < sortedTimeCtrls.length - 1) {
              // 如果不是最后一个时间段，结束时间为下一个时间段的开始时间
              const nextCtrl = sortedTimeCtrls[index + 1];
              endTime = `${String(nextCtrl.hour).padStart(2, '0')}:${String(
                nextCtrl.minute,
              ).padStart(2, '0')}:${String(nextCtrl.second).padStart(2, '0')}`;
            }

            return {
              timeKey: ctrl.timeKey,
              startTime: `${String(ctrl.hour).padStart(2, '0')}:${String(ctrl.minute).padStart(
                2,
                '0',
              )}:${String(ctrl.second).padStart(2, '0')}`,
              endTime,
              chargeType:
                ctrl.ctrlType === 0 || ctrl.ctrlType === 2
                  ? intl.formatMessage({
                      id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge',
                    })
                  : ctrl.ctrlType === 1
                  ? intl.formatMessage({
                      id: 'strategyAction.chargeDischargeStrategy.chargeAndDischarge',
                    })
                  : ctrl.ctrlType === 3
                  ? intl.formatMessage({
                      id: 'strategyAction.chargeDischargeStrategy.onlyCharge',
                    })
                  : ctrl.ctrlType === 4
                  ? intl.formatMessage({
                      id: 'strategyAction.chargeDischargeStrategy.onlyDischarge',
                    })
                  : intl.formatMessage({
                      id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge',
                    }),
              timeType:
                ctrl.peakValleyType === 1
                  ? intl.formatMessage({ id: 'strategyAction.electricityPrices.highPeak' })
                  : ctrl.peakValleyType === 2
                  ? intl.formatMessage({ id: 'strategyAction.electricityPrices.peak' })
                  : ctrl.peakValleyType === 3
                  ? intl.formatMessage({ id: 'strategyAction.electricityPrices.midPeak' })
                  : intl.formatMessage({ id: 'strategyAction.electricityPrices.offPeak' }),
              socLower: ctrl.socLowLimit,
              socUpper: ctrl.socUpperLimit,
              targetPower: ctrl.targetPower,
            };
          });

          return {
            ...item,
            children: (
              <ProTable
                columns={createColumns({
                  onEdit: handleEditTimeSlot,
                  // eslint-disable-next-line @typescript-eslint/no-use-before-define
                  onDelete: handleDeleteTimeSlot,
                })}
                dataSource={tableData}
                search={false}
                rowKey="timeKey"
                options={false}
              />
            ),
          };
        }
        return { ...item };
      });
    };

    const handleDeleteTimeSlot = useCallback(
      async (timeKey: string) => {
        try {
          console.log('Delete Slot - Current State:', {
            activeStrategyTab,
            tempSchemes: tempSchemesRef.current,
            timeKey,
          });

          if (!timeKey) {
            message.error(
              intl.formatMessage({ id: 'strategyAction.error.invalidTimeSlotIdentifier' }),
            );
            return;
          }

          // 使用最新的 ref 数据
          const currentTempSchemes = [...tempSchemesRef.current];

          // 确保 activeStrategyTab 有值
          if (!activeStrategyTab) {
            message.error(
              intl.formatMessage({ id: 'strategyAction.error.pleaseSelectStrategyPlan' }),
            );
            return;
          }

          const schemeIndex = currentTempSchemes.findIndex(
            (scheme: TimeScheme) => scheme.id === activeStrategyTab,
          );

          if (schemeIndex === -1) {
            message.error(intl.formatMessage({ id: 'strategyAction.error.noCurrentStrategyPlan' }));
            return;
          }

          const currentScheme = currentTempSchemes[schemeIndex];
          const timeCtrlIndex = currentScheme.timeCtrls.findIndex(
            (ctrl: TimeCtrl) => ctrl.timeKey === timeKey,
          );

          if (timeCtrlIndex === -1) {
            message.error(intl.formatMessage({ id: 'strategyAction.error.noTimeSlotToDelete' }));
            return;
          }

          // 调用接口删除时间段
          const res = await strategySchemeControllerImplUpdateTimeScheme(
            { scheme_id: activeStrategyTab.toString() },
            {
              schemeName: currentScheme.schemeName,
              timeCtrls: currentScheme.timeCtrls.filter((ctrl) => ctrl.timeKey !== timeKey),
            },
          );

          if (res.success) {
            // 删除时间段
            currentScheme.timeCtrls.splice(timeCtrlIndex, 1);

            // 更新状态
            updateTempSchemes(currentTempSchemes);

            // 更新表格显示逻辑
            const newStrategyItems = updateStrategyTableDisplay(
              currentTempSchemes,
              activeStrategyTab,
              strategyItems,
            );

            setStrategyItems(newStrategyItems);
            message.success(
              intl.formatMessage({ id: 'strategyAction.error.timeSlotDeleteSuccess' }),
            );
          } else {
            message.error(
              res.message ||
                intl.formatMessage({ id: 'strategyAction.error.timeSlotDeleteFailed' }),
            );
          }
        } catch (error) {
          console.error('删除时段失败:', error);
          message.error(intl.formatMessage({ id: 'strategyAction.error.timeSlotDeleteFailed' }));
        }
      },
      [activeStrategyTab, handleEditTimeSlot, createColumns, updateStrategyTableDisplay],
    );

    // Modify handleAddTimeSlot function
    const handleAddTimeSlot = async (values: any) => {
      try {
        const currentScheme = tempSchemes.find((scheme) => scheme.id === activeStrategyTab);
        if (!currentScheme) {
          message.error(intl.formatMessage({ id: 'strategyAction.error.noCurrentStrategyPlan' }));
          return false;
        }

        // 生成唯一的 timeKey
        const timeKey = `${values.startTime}_${Date.now()}`;

        const timeCtrlData = {
          timeKey, // 添加唯一的 timeKey
          startTime: values.startTime,
          hour: Number(values.startTime.split(':')[0]),
          minute: Number(values.startTime.split(':')[1]),
          second: Number(values.startTime.split(':')[2]),
          peakValleyType: getPeakValleyType(values.timeType),
          ctrlType: getCtrlType(intl, values.chargeType),
          targetPower: Number(values.targetPower),
          socUpperLimit: Number(values.socUpper),
          socLowLimit: Number(values.socLower),
        };

        // 直接调用更新或新增接口
        let res;
        if (isEditMode) {
          // 编辑模式
          res = await strategySchemeControllerImplUpdateTimeScheme(
            { scheme_id: currentScheme.id.toString() },
            {
              schemeName: currentScheme.schemeName,
              timeCtrls: currentScheme.timeCtrls.map((ctrl) =>
                ctrl.timeKey === editingTimeCtrl?.originalTimeKey ? timeCtrlData : ctrl,
              ),
            },
          );
        } else {
          // 新增模式
          res = await strategySchemeControllerImplUpdateTimeScheme(
            { scheme_id: currentScheme.id.toString() },
            {
              schemeName: currentScheme.schemeName,
              timeCtrls: [...currentScheme.timeCtrls, timeCtrlData],
            },
          );
        }

        if (res.success) {
          // 更新本地状态
          const updatedSchemes = tempSchemes.map((scheme) => {
            if (scheme.id === activeStrategyTab) {
              const updatedTimeCtrls = isEditMode
                ? scheme.timeCtrls.map((ctrl) =>
                    ctrl.timeKey === editingTimeCtrl?.originalTimeKey ? timeCtrlData : ctrl,
                  )
                : [...scheme.timeCtrls, timeCtrlData];

              return {
                ...scheme,
                timeCtrls: updatedTimeCtrls,
              };
            }
            return scheme;
          });

          updateTempSchemes(updatedSchemes);

          // 更新表格显示
          const newStrategyItems = updateStrategyTableDisplay(
            updatedSchemes,
            activeStrategyTab,
            strategyItems,
          );
          setStrategyItems(newStrategyItems);

          setAddTimeSlotModalVisible(false);
          setEditingTimeCtrl(null);
          setIsEditMode(false);
          form.resetFields();

          message.success(
            intl.formatMessage({
              id: isEditMode
                ? 'strategyAction.error.timeSlotEditSuccess'
                : 'strategyAction.error.timeSlotAddSuccess',
            }),
          );
          return true;
        } else {
          message.error(
            res.message ||
              intl.formatMessage({
                id: isEditMode
                  ? 'strategyAction.error.timeSlotEditFailed'
                  : 'strategyAction.error.timeSlotAddFailed',
              }),
          );
          return false;
        }
      } catch (error) {
        console.error('更新时间段失败:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.updateTimeSlotFailed' }));
        return false;
      }
    };

    // 修改新增策略方案的处理方法
    const handleAddNewStrategy = async (values: { strategyName: string }) => {
      try {
        // 检查是否与现有方案重名
        const isDuplicate = tempSchemes.some((scheme) => scheme.schemeName === values.strategyName);
        if (isDuplicate) {
          message.error(
            intl.formatMessage({ id: 'strategyAction.error.strategyNameAlreadyExists' }),
          );
          return false;
        }
        const params = {
          schemeName: values.strategyName,
          timeCtrls: [],
        };

        const res = await strategySchemeControllerImplAddTimeScheme(params);

        if (res.success) {
          // 修改这里：直接使用返回的数据结构
          const newStrategy: TimeScheme = {
            id: res.data.id, // 使用返回的 id
            schemeName: res.data.schemeName,
            timeCtrls: res.data.timeCtrls || [],
          };

          // 更新本地状态
          const updatedSchemes = [...tempSchemesRef.current, newStrategy];
          updateTempSchemes(updatedSchemes);

          // 更新 strategyItems
          const newStrategyItems = [
            ...strategyItems,
            {
              key: String(newStrategy.id), // 确保使用正确的 id
              label: newStrategy.schemeName,
              children: (
                <ProTable
                  columns={createColumns({
                    onEdit: handleEditTimeSlot,
                    onDelete: handleDeleteTimeSlot,
                  })}
                  dataSource={[]}
                  search={false}
                  rowKey="timeKey"
                  options={false}
                />
              ),
            },
          ];

          setStrategyItems(newStrategyItems);
          setActiveStrategyTab(newStrategy.id);
          setAddStrategyModalVisible(false);
          message.success(
            intl.formatMessage({ id: 'strategyAction.error.strategyPlanAddSuccess' }),
          );
          return true;
        } else {
          message.error(
            res.message || intl.formatMessage({ id: 'strategyAction.error.strategyPlanAddFailed' }),
          );
          return false;
        }
      } catch (error) {
        console.error('新增策略方案失败:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.strategyPlanAddFailed' }));
        return false;
      }
    };

    // 获取时间策略方案列表
    const getTimeSchemes = async () => {
      try {
        const res = await strategySchemeControllerImplListTimeScheme();
        if (res.success && res.data) {
          const processedSchemes = res.data.map((scheme: any) => ({
            ...scheme,
            timeCtrls: scheme.timeCtrls.map((ctrl: any) => ({
              ...ctrl,
              timeKey: ctrl.startTime,
            })),
          }));

          // 更新 tempSchemes
          updateTempSchemes(processedSchemes);
          setTimeSchemes(processedSchemes);

          // 更新 strategyItems
          const newStrategyItems = processedSchemes.map((scheme) => ({
            key: String(scheme.id),
            label: scheme.schemeName,
            children: (
              <ProTable
                columns={createColumns({
                  onEdit: handleEditTimeSlot,
                  onDelete: handleDeleteTimeSlot,
                })}
                dataSource={scheme.timeCtrls.map((ctrl) => ({
                  timeKey: ctrl.timeKey,
                  startTime: ctrl.startTime,
                  chargeType:
                    ctrl.ctrlType === 0 || ctrl.ctrlType === 2
                      ? intl.formatMessage({
                          id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge',
                        })
                      : ctrl.ctrlType === 1
                      ? intl.formatMessage({
                          id: 'strategyAction.chargeDischargeStrategy.chargeAndDischarge',
                        })
                      : ctrl.ctrlType === 3
                      ? intl.formatMessage({
                          id: 'strategyAction.chargeDischargeStrategy.onlyCharge',
                        })
                      : ctrl.ctrlType === 4
                      ? intl.formatMessage({
                          id: 'strategyAction.chargeDischargeStrategy.onlyDischarge',
                        })
                      : intl.formatMessage({
                          id: 'strategyAction.chargeDischargeStrategy.noChargeDischarge',
                        }),
                  timeType:
                    ctrl.peakValleyType === 1
                      ? intl.formatMessage({ id: 'strategyAction.electricityPrices.highPeak' })
                      : ctrl.peakValleyType === 2
                      ? intl.formatMessage({ id: 'strategyAction.electricityPrices.peak' })
                      : ctrl.peakValleyType === 3
                      ? intl.formatMessage({ id: 'strategyAction.electricityPrices.midPeak' })
                      : intl.formatMessage({ id: 'strategyAction.electricityPrices.offPeak' }),
                  socLower: ctrl.socLowLimit,
                  socUpper: ctrl.socUpperLimit,
                  targetPower: ctrl.targetPower,
                }))}
                search={false}
                rowKey="timeKey"
                options={false}
              />
            ),
          }));

          setStrategyItems(newStrategyItems);

          return processedSchemes;
        }
        return [];
      } catch (error) {
        console.error('获取时间策略方案失败:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.getTimeStrategyPlanFailed' }));
        return [];
      }
    };

    // Hide all edit buttons when readOnly is true
    const showActions = !readOnly;
    // 修改获取数据的方法
    const getList = async (areaId?: number) => {
      try {
        const res = await strategyControllerImplShowTimedStrategy({
          headers: {
            'Station-Area': areaId ? areaId.toString() : null,
          },
        });
        if (res.success && res.data) {
          setStrategyData(res.data);
          const isWeekMode = res.data.timedStrategy?.runType === 1;
          setExecutionMode(isWeekMode ? 'week' : 'date');

          // 处理日期策略数据
          if (!isWeekMode && res.data.timedStrategy?.dates) {
            // 按月份对策略进行分组
            const grouped = res.data.timedStrategy.dates.reduce((acc: GroupedStrategy, curr) => {
              if (!acc[curr.month]) {
                acc[curr.month] = [];
              }
              acc[curr.month].push(curr);
              return acc;
            }, {});
            setGroupedStrategies(grouped);

            // 设置选中的月份
            const selectedMonthSet = new Set(
              res.data.timedStrategy.dates.map((item: any) => tagsData[item.month - 1]),
            );
            setSelectedMonths(Array.from(selectedMonthSet));
          }

          if (isWeekMode && res.data.timedStrategy?.weeks) {
            // Transform the data into an array of WeekStrategy objects
            const weekStrategies: WeekStrategy[] = res.data.timedStrategy.weeks
              .map((schemeId: number | null, index: number) => {
                if (schemeId !== null) {
                  return {
                    weekDay: index === 0 ? 7 : index,
                    schemeId: schemeId,
                  };
                }
                return null;
              })
              .filter((item): item is WeekStrategy => item !== null);

            setWeekStrategyList(weekStrategies);

            // Set selected weeks
            const selectedWeeks = res.data.timedStrategy.weeks
              .map((schemeId: number | null, index: number) =>
                schemeId !== null ? weekTagsData[index] : null,
              )
              .filter((week): week is string => week !== null);
            setSelectedWeek(selectedWeeks);
          }
        }
      } catch (error) {
        console.error('获取策略数据败:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.getStrategyDataFailed' }));
      }
    };

    useEffect(() => {
      if (strategyData) {
        const isWeekMode = strategyData.timedStrategy?.runType === 1;
        setExecutionMode(isWeekMode ? 'week' : 'date');

        // 处理日期策略数据
        if (!isWeekMode && strategyData.timedStrategy?.dates) {
          // 按月份对策略进行分组
          const grouped = strategyData.timedStrategy.dates.reduce((acc: GroupedStrategy, curr) => {
            if (!acc[curr.month]) {
              acc[curr.month] = [];
            }
            acc[curr.month].push(curr);
            return acc;
          }, {});
          setGroupedStrategies(grouped);

          // 设置选中的月份
          const selectedMonthSet = new Set(
            strategyData.timedStrategy.dates.map((item: any) => tagsData[item.month - 1]),
          );
          setSelectedMonths(Array.from(selectedMonthSet));
        }

        if (isWeekMode && strategyData.timedStrategy?.weeks) {
          // Transform the data into an array of WeekStrategy objects
          const weekStrategies: WeekStrategy[] = strategyData.timedStrategy.weeks
            .map((schemeId: number | null, index: number) => {
              if (schemeId !== null) {
                return {
                  weekDay: index === 0 ? 7 : index,
                  schemeId: schemeId,
                };
              }
              return null;
            })
            .filter((item): item is WeekStrategy => item !== null);

          setWeekStrategyList(weekStrategies);

          // Set selected weeks
          const selectedWeeks = strategyData.timedStrategy.weeks
            .map((schemeId: number | null, index: number) =>
              schemeId !== null ? weekTagsData[index] : null,
            )
            .filter((week): week is string => week !== null);
          setSelectedWeek(selectedWeeks);
        }
      }
    }, [strategyData]);

    // 修改添加日期策略的方法
    const handleAddDateStrategy = () => {
      const monthIndex = tagsData.indexOf(currentMonth) + 1;
      const nextMonthFirst = getNextMonthFirstDay(monthIndex);

      // 如果当前月份没有策略，则添加月初和次月第一天两个默认策略
      if (currentMonthStrategies.length === 0) {
        const defaultStrategies = [
          {
            month: monthIndex,
            day: 1,
            timeSchemeSn: null,
            isNew: true,
          },
          {
            month: nextMonthFirst.month,
            day: nextMonthFirst.day,
            timeSchemeSn: null,
            isNew: true,
            isLastDay: true,
          },
        ];
        setCurrentMonthStrategies(defaultStrategies);
      } else {
        // 找到插入位置（排除最后一条记录，因为最后一条是次月第一天）
        const workingStrategies = currentMonthStrategies.slice(0, -1);

        // 计算新策略的日期
        const newDay = calculateMiddleDay(workingStrategies);

        const newStrategy = {
          month: monthIndex,
          day: newDay,
          timeSchemeSn: null,
          isNew: true,
        };

        // 保持最后一条记录（次月第一天）
        const lastStrategy = currentMonthStrategies[currentMonthStrategies.length - 1];

        // 合并并排序策略（排除最后一条记录）
        const sortedWorkingStrategies = sortDateStrategies([...workingStrategies, newStrategy]);

        // 添加回最后一条记录
        const updatedStrategies = [...sortedWorkingStrategies, lastStrategy];
        setCurrentMonthStrategies(updatedStrategies);
      }
    };

    // 添加删除策略的方法
    const handleDeleteDateStrategies = () => {
      if (selectedStrategyKeys.length === 0) {
        message.warning(
          intl.formatMessage({ id: 'strategyAction.error.pleaseSelectStrategyToDelete' }),
        );
        return;
      }

      const newStrategies = currentMonthStrategies.filter(
        (_, index) => !selectedStrategyKeys.includes(index.toString()),
      );
      setCurrentMonthStrategies(newStrategies);
      setSelectedStrategyKeys([]); // 清空选中
      message.success(intl.formatMessage({ id: 'strategyAction.error.deleteSuccess' }));
    };

    // 修改空状态的渲染逻辑
    const renderEmptyState = () => {
      const monthIndex = tagsData.indexOf(currentMonth) + 1;
      const nextMonthFirst = getNextMonthFirstDay(monthIndex);

      // 创建默认的策略数组
      const defaultStrategies = [
        {
          month: monthIndex,
          day: 1,
          timeSchemeSn: null,
          isNew: true,
        },
        {
          month: nextMonthFirst.month,
          day: nextMonthFirst.day,
          timeSchemeSn: null,
          isLastDay: true,
        },
      ];

      return (
        <div className={styles.timelineFormContainer}>
          {!readOnly && (
            <div className={styles.dateStrategyActions}>
              <Space>
                <HandleBtn handleType="add" onClick={handleAddDateStrategy}>
                  {intl.formatMessage({ id: 'strategyAction.error.addNew' })}
                </HandleBtn>
                <HandleBtn handleType="delete" onClick={handleDeleteDateStrategies}>
                  {intl.formatMessage({ id: 'strategyAction.error.delete' })}
                </HandleBtn>
              </Space>
            </div>
          )}
          {defaultStrategies.map((strategy, index) => (
            <div key={index} className={styles.formItemWrapper}>
              <div className={styles.timelineNode} style={{ top: index === 0 ? '12px' : '12px' }} />
              <ProFormGroup>
                {
                  <ProFormCheckbox
                    name={`selected_${index}`}
                    fieldProps={{
                      checked: selectedStrategyKeys.includes(index.toString()),
                      onChange: (e: CheckboxChangeEvent) => {
                        if (e.target.checked) {
                          setSelectedStrategyKeys([...selectedStrategyKeys, index.toString()]);
                        } else {
                          setSelectedStrategyKeys(
                            selectedStrategyKeys.filter((key) => key !== index.toString()),
                          );
                        }
                      },
                      disabled: readOnly || index === 0 || strategy.isLastDay,
                    }}
                    colProps={{ span: 1 }}
                  />
                }
                <ProFormDatePicker
                  name={`startDate_${index}`}
                  label={intl.formatMessage({ id: 'strategyAction.error.startDate' })}
                  rules={[
                    {
                      required: true,
                      message: intl.formatMessage({
                        id: 'strategyAction.error.pleaseSelectStartDate',
                      }),
                    },
                  ]}
                  fieldProps={{
                    style: { width: '100%' },
                    format: 'MM-DD',
                    disabledDate: (current) => {
                      if (strategy.isLastDay) {
                        const nextMonth = monthIndex === 12 ? 1 : monthIndex + 1;
                        return (
                          current && (current.date() !== 1 || current.month() !== nextMonth - 1)
                        );
                      }
                      return current && current.month() !== tagsData.indexOf(currentMonth);
                    },
                    disabled: strategy.isLastDay || readOnly,
                  }}
                  initialValue={
                    strategy.day
                      ? dayjs(
                          `${dayjs().year()}-${String(strategy.month).padStart(2, '0')}-${String(
                            strategy.day,
                          ).padStart(2, '0')}`,
                        )
                      : undefined
                  }
                  colProps={{ span: 12 }}
                />
                {!strategy.isLastDay && (
                  <div className={styles.schemeSelect}>
                    <ProFormSelect
                      name={`timeScheme_${index}`}
                      label={intl.formatMessage({ id: 'strategyAction.error.timeStrategyPlan' })}
                      initialValue={strategy.timeSchemeSn}
                      rules={[
                        {
                          required: false,
                          message: intl.formatMessage({
                            id: 'strategyAction.error.pleaseSelectTimeStrategyPlan',
                          }),
                        },
                      ]}
                      options={timeSchemes.map((scheme) => ({
                        label: scheme.schemeName,
                        value: scheme.id,
                      }))}
                      width="md"
                      colProps={{ span: 24 }}
                      labelCol={{ span: 10 }}
                      disabled={readOnly}
                    />
                  </div>
                )}
              </ProFormGroup>
            </div>
          ))}
        </div>
      );
    };

    // 修改弹窗内容渲染方法
    const renderModalContent = () => {
      if (executionMode === 'date' && currentMonth) {
        if (currentMonthStrategies.length === 0) {
          return renderEmptyState();
        }

        // 确保策略列表中包含次月第一天
        const monthIndex = tagsData.indexOf(currentMonth) + 1;
        const nextMonthFirst = getNextMonthFirstDay(monthIndex);

        // 过滤掉可能存在的旧的次月第一天记录
        const workingStrategies = currentMonthStrategies.filter((strategy) => !strategy.isLastDay);

        // 添加次月第一天记录
        const displayStrategies = [
          ...workingStrategies,
          {
            month: nextMonthFirst.month,
            day: nextMonthFirst.day,
            timeSchemeSn: null,
            isLastDay: true,
          },
        ];

        console.log('displayStrategies---', { year: dayjs().year() });

        return (
          <div style={{ width: '100%' }}>
            <div className={styles.dateStrategyActions}>
              {!readOnly && (
                <Space>
                  <HandleBtn handleType="add" onClick={handleAddDateStrategy}>
                    {intl.formatMessage({ id: 'strategyAction.error.addNew' })}
                  </HandleBtn>
                  <HandleBtn handleType="delete" onClick={handleDeleteDateStrategies}>
                    {intl.formatMessage({ id: 'strategyAction.error.delete' })}
                  </HandleBtn>
                </Space>
              )}
            </div>
            <div className={styles.timelineFormContainer}>
              {displayStrategies.map((strategy, index) => (
                <div key={index} className={styles.formItemWrapper}>
                  <div
                    className={styles.timelineNode}
                    style={{ top: index === 0 ? '12px' : '12px' }}
                  />
                  <ProFormGroup>
                    {
                      <ProFormCheckbox
                        name={`selected_${index}`}
                        fieldProps={{
                          checked: selectedStrategyKeys.includes(index.toString()),
                          onChange: (e: CheckboxChangeEvent) => {
                            if (e.target.checked) {
                              setSelectedStrategyKeys([...selectedStrategyKeys, index.toString()]);
                            } else {
                              setSelectedStrategyKeys(
                                selectedStrategyKeys.filter((key) => key !== index.toString()),
                              );
                            }
                          },
                          disabled: readOnly || index === 0 || strategy.isLastDay,
                        }}
                        colProps={{ span: 1 }}
                      />
                    }
                    <ProFormDatePicker
                      name={`startDate_${index}`}
                      label={intl.formatMessage({ id: 'strategyAction.error.startDate' })}
                      rules={[
                        {
                          required: true,
                          message: intl.formatMessage({
                            id: 'strategyAction.error.pleaseSelectStartDate',
                          }),
                        },
                      ]}
                      fieldProps={{
                        style: { width: '100%' },
                        format: 'MM-DD',
                        disabledDate: (current) => {
                          if (strategy.isLastDay) {
                            const nextMonth = monthIndex === 12 ? 1 : monthIndex + 1;
                            return (
                              current && (current.date() !== 1 || current.month() !== nextMonth - 1)
                            );
                          }
                          return current && current.month() !== tagsData.indexOf(currentMonth);
                        },
                        disabled: strategy.isLastDay || readOnly,
                      }}
                      initialValue={
                        strategy.day
                          ? dayjs(
                              `${dayjs().year()}-${String(strategy.month).padStart(
                                2,
                                '0',
                              )}-${String(strategy.day).padStart(2, '0')}`,
                            )
                          : undefined
                      }
                      colProps={{ span: 11 }}
                    />
                    {!strategy.isLastDay && (
                      <div className={styles.schemeSelect}>
                        <ProFormSelect
                          name={`timeScheme_${index}`}
                          label={intl.formatMessage({
                            id: 'strategyAction.error.timeStrategyPlan',
                          })}
                          initialValue={strategy.timeSchemeSn}
                          rules={[
                            {
                              required: false,
                              message: intl.formatMessage({
                                id: 'strategyAction.error.pleaseSelectTimeStrategyPlan',
                              }),
                            },
                          ]}
                          options={timeSchemes.map((scheme) => ({
                            label: scheme.schemeName,
                            value: scheme.id,
                          }))}
                          width="md"
                          colProps={{ span: 24 }}
                          labelCol={{ span: 10 }}
                          disabled={readOnly}
                        />
                      </div>
                    )}
                  </ProFormGroup>
                </div>
              ))}
            </div>
          </div>
        );
      }

      if (executionMode === 'week' && currentEditingWeekIndex !== null) {
        const weekDay = currentEditingWeekIndex === 0 ? 7 : currentEditingWeekIndex;
        const currentStrategy = weekStrategyList.find((s) => s.weekDay === weekDay);

        // Directly return the select form
        return (
          <ProFormSelect
            name="timeScheme"
            label={`${weekTagsData[currentEditingWeekIndex]}${intl.formatMessage({
              id: 'strategyAction.error.strategyPlan',
            })}`}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'strategyAction.error.pleaseSelectTimeStrategyPlan',
                }),
              },
            ]}
            options={timeSchemes.map((scheme) => ({
              label: scheme.schemeName,
              value: scheme.id,
            }))}
            initialValue={currentStrategy?.schemeId}
            width="md"
            disabled={readOnly}
          />
        );
      }

      return null;
    };

    // 修改弹窗提交方法中的日期策略处理部分
    const handleModalSubmit = async (values: any) => {
      // 如果是只读模式，直接返回
      if (readOnly) {
        return true;
      }

      if (executionMode === 'date') {
        try {
          const monthIndex = tagsData.indexOf(currentMonth) + 1;
          // 获取所有非最后一天的策略
          const normalStrategies = currentMonthStrategies
            .filter((strategy) => !strategy.isLastDay)
            .map((strategy, index) => {
              const dateValue = values[`startDate_${index}`];
              const schemeValue = values[`timeScheme_${index}`];

              return {
                month: monthIndex,
                day: dateValue ? dayjs(dateValue).date() : 1,
                timeSchemeSn: schemeValue,
              };
            });

          // 添加次月第一天作为结束时间
          const nextMonthFirst = getNextMonthFirstDay(monthIndex);
          const formattedStrategies = [
            ...normalStrategies,
            {
              month: nextMonthFirst.month,
              day: nextMonthFirst.day,
              timeSchemeSn: null,
              isLastDay: true,
            },
          ];

          // 对策略进行排序
          const sortedStrategies = sortDateStrategies(formattedStrategies);

          // 更新分组策略数据
          const newGroupedStrategies = {
            ...groupedStrategies,
            [monthIndex]: sortedStrategies,
          };
          setGroupedStrategies(newGroupedStrategies);

          // 更新 selectedMonths
          const updatedSelectedMonths = [...new Set([...selectedMonths, currentMonth])];
          setSelectedMonths(updatedSelectedMonths);

          message.success(intl.formatMessage({ id: 'strategyAction.error.saveSuccess' }));
          setModalVisible(false);
        } catch (error) {
          console.error('保存策略失败:', error);
          message.error(intl.formatMessage({ id: 'strategyAction.error.saveFailed' }));
        }
      }
      if (executionMode === 'week' && currentEditingWeekIndex !== null) {
        try {
          const weekDay = currentEditingWeekIndex === 0 ? 7 : currentEditingWeekIndex;
          const newStrategy = { weekDay, schemeId: values.timeScheme };

          // 更新周策略列表
          const newWeekStrategyList = [...weekStrategyList];
          const existingIndex = newWeekStrategyList.findIndex((s) => s.weekDay === weekDay);

          if (existingIndex >= 0) {
            newWeekStrategyList[existingIndex] = newStrategy;
          } else {
            newWeekStrategyList.push(newStrategy);
          }

          setWeekStrategyList(newWeekStrategyList);

          // 更新选中的周标签
          if (!selectedWeek.includes(weekTagsData[currentEditingWeekIndex])) {
            setSelectedWeek((prev) => [...prev, weekTagsData[currentEditingWeekIndex]]);
          }

          message.success(intl.formatMessage({ id: 'strategyAction.error.strategyUpdateSuccess' }));
          setModalVisible(false); // 添加这行来关闭弹窗
        } catch (error) {
          console.error('更新策略失败:', error);
          message.error(intl.formatMessage({ id: 'strategyAction.error.strategyUpdateFailed' }));
        }
      }
    };

    // 修改弹窗关闭处理
    const handleModalVisibleChange = (visible: boolean) => {
      if (!visible) {
        setCurrentEditingWeekIndex(null);
      }
      setModalVisible(visible);
    };

    // 添加一个 key 状来强制刷新表单
    const [formKey] = useState(0);

    // 修改新增按钮的处理函数
    // const handleAddDateStrategy = () => {
    //   setDateStrategyList(prev => [
    //     ...prev,
    //     {
    //       startDate: '',
    //       schemeId: undefined
    //     }
    //   ]);
    //   // 强制更新表单
    //   setFormKey(prev => prev + 1);
    // };

    // 添加一个方法来收集间策略数据
    const getTimeStrategyData = () => {
      const isWeekMode = executionMode === 'week';

      return {
        runType: isWeekMode ? 1 : 2,
        // 处理周策略
        weeks: isWeekMode
          ? Array(7)
              .fill(null)
              .map((_, index) => {
                const weekStrategy = weekStrategyList.find(
                  (s) => s.weekDay === (index === 0 ? 7 : index),
                );
                return weekStrategy?.schemeId || null;
              })
          : [],
        // 处理日期策略，过滤掉最后一天（次月第一天）的据
        dates: !isWeekMode
          ? Object.entries(groupedStrategies).flatMap(([month, strategies]) =>
              strategies
                .filter((strategy) => !strategy.isLastDay) // 添加这行过滤条件
                .map((strategy) => ({
                  month: parseInt(month),
                  day: strategy.day,
                  timeSchemeSn: strategy.timeSchemeSn,
                })),
            )
          : [],
        // 时间方案数据保持不变
        timeSchemes: timeSchemes.map((scheme) => ({
          id: scheme.id,
          schemeName: scheme.schemeName,
          timeCtrls: scheme.timeCtrls.map((ctrl) => ({
            startTime: `${String(ctrl.hour).padStart(2, '0')}:${String(ctrl.minute).padStart(
              2,
              '0',
            )}:${String(ctrl.second).padStart(2, '0')}`,
            hour: ctrl.hour,
            minute: ctrl.minute,
            second: ctrl.second,
            peakValleyType: ctrl.peakValleyType,
            ctrlType: ctrl.ctrlType,
            targetPower: ctrl.targetPower,
            socUpperLimit: ctrl.socUpperLimit,
            socLowLimit: ctrl.socLowLimit,
          })),
        })),
      };
    };
    // 暴露方法给父组件
    React.useImperativeHandle<any, any>(ref, () => ({
      getTimeStrategyData,
    }));

    // 修改组件挂载时的数据获取
    useEffect(() => {
      const initData = async () => {
        console.log('Component mounted, fetching schemes...');
        await getTimeSchemes();
      };
      initData();
    }, []);

    // 修改 activeStrategyTab 变化的监听
    useEffect(() => {
      const updateData = async () => {
        console.log('activeStrategyTab changed to:', activeStrategyTab);
        if (activeStrategyTab && tempSchemes.length === 0) {
          await getTimeSchemes();
        }
      };
      updateData();
    }, [activeStrategyTab, tempSchemes.length]);

    useEffect(() => {
      console.log('tempSchemes updated:', tempSchemes);
      tempSchemesRef.current = tempSchemes;
    }, [tempSchemes]);

    // 添加监听 activeStrategyTab 变化的 effect
    useEffect(() => {
      if (activeStrategyTab !== null) {
        const newStrategyItems = updateStrategyTableDisplay(
          tempSchemesRef.current,
          activeStrategyTab,
          strategyItems,
        );
        setStrategyItems(newStrategyItems);
      }
    }, [activeStrategyTab]);

    // 添加数据监控
    useEffect(() => {
      console.log('tempSchemes updated:', tempSchemesRef.current);
    }, [tempSchemes]);

    useEffect(() => {
      console.log('strategyItems updated:', strategyItems);
    }, [strategyItems]);

    // 修改删除策略方案的处理函数
    const handleRemoveStrategy = async (targetKey: string) => {
      try {
        const targetId = Number(targetKey);

        // 调删除接口
        const res = await strategySchemeControllerImplDeleteTimeScheme({
          scheme_id: targetKey,
        });

        if (res.success) {
          const currentSchemes = tempSchemesRef.current;
          // 过滤掉要删除的策略方案
          const newSchemes = currentSchemes.filter((scheme) => scheme.id !== targetId);

          // 更新所有相关状态
          updateTempSchemes(newSchemes);
          setTimeSchemes(newSchemes);

          // 更新策略项显示
          const newStrategyItems = strategyItems.filter((item) => item.key !== targetKey);
          setStrategyItems(newStrategyItems);

          // 如果删除的是当前激活的tab，需要更新activeStrategyTab
          if (targetId === activeStrategyTab) {
            // 选择新的活动tab
            const newActiveId = newSchemes.length > 0 ? newSchemes[0].id : null;
            setActiveStrategyTab(newActiveId);
          }

          message.success(
            intl.formatMessage({ id: 'strategyAction.error.strategyPlanDeleteSuccess' }),
          );
          return true;
        }
        return false;
      } catch (error) {
        // 捕获到错误时使用 Modal 显示错误
        Modal.error({
          title: intl.formatMessage({ id: 'strategyAction.error.deleteFailed' }),
          content: intl.formatMessage({ id: 'strategyAction.error.strategyPlanDeleteFailed' }),
        });
        return false;
      }
    };

    // 修改 handleEdit 函数，增加对删除操作返回值的处理
    const handleEdit = (
      targetKey: React.MouseEvent | React.KeyboardEvent | string,
      action: 'add' | 'remove',
    ) => {
      if (action === 'add') {
        setAddStrategyModalVisible(true);
      } else if (action === 'remove') {
        // 如果是只读模式，不允许删除
        if (readOnly) {
          return;
        }
        // 使用 Modal.confirm 确认删除
        Modal.confirm({
          title: intl.formatMessage({ id: 'strategyAction.error.confirmDelete' }),
          content: intl.formatMessage({ id: 'strategyAction.error.confirmDeleteStrategy' }),
          okText: intl.formatMessage({ id: 'strategyAction.baseColumns.confirm' }),
          cancelText: intl.formatMessage({ id: 'strategyAction.baseColumns.cancel' }),
          onOk: () => handleRemoveStrategy(targetKey as string),
        });
      }
    };

    // 添加 useEffect 监听 currentAreaId 变化
    useEffect(() => {
      if (currentAreaId) {
        getList(currentAreaId);
      }
    }, [currentAreaId]);

    // 添加编辑 tab 名称的状态
    const [editTabNameModalVisible, setEditTabNameModalVisible] = useState(false);
    const [currentEditingTabName, setCurrentEditingTabName] = useState('');
    const [currentEditingTabKey, setCurrentEditingTabKey] = useState<number | null>(null);

    const handleEditTabName = async (values: { tabName: string }) => {
      try {
        // 校验名称
        if (!values.tabName?.trim()) {
          message.error(
            intl.formatMessage({ id: 'strategyAction.error.strategyNameCannotBeEmpty' }),
          );
          return false;
        }

        // 果没有选中的 tab，不执行操作
        if (!currentEditingTabKey) {
          message.error(
            intl.formatMessage({ id: 'strategyAction.error.pleaseSelectStrategyToEdit' }),
          );
          return false;
        }

        // 验证名称是否重复
        if (!validateStrategyName(values.tabName, tempSchemes, currentEditingTabKey)) {
          return false;
        }

        // 如果是临时策略（ID为负数），只更新本地状态
        if (currentEditingTabKey < 0) {
          // 更新本地状态
          const updatedSchemes = tempSchemes.map((scheme) =>
            scheme.id === currentEditingTabKey ? { ...scheme, schemeName: values.tabName } : scheme,
          );

          // 更新 tempSchemes
          updateTempSchemes(updatedSchemes);

          // 更新 strategyItems
          const updatedStrategyItems = strategyItems.map((item) =>
            item.key === currentEditingTabKey.toString()
              ? { ...item, label: values.tabName }
              : item,
          );
          setStrategyItems(updatedStrategyItems);

          message.success(
            intl.formatMessage({ id: 'strategyAction.error.strategyNameUpdateSuccess' }),
          );
          setEditTabNameModalVisible(false);
          setCurrentEditingTabName('');
          setCurrentEditingTabKey(null);
          return true;
        }

        // 对于已保存的策略，继续使用原有的API调用逻辑
        const currentScheme = tempSchemes.find((scheme) => scheme.id === currentEditingTabKey);
        if (!currentScheme) {
          message.error(intl.formatMessage({ id: 'strategyAction.error.noCurrentStrategyPlan' }));
          return false;
        }

        const params = {
          schemeName: values.tabName,
          timeCtrls: currentScheme.timeCtrls.map((ctrl) => ({
            startTime: `${String(ctrl.hour).padStart(2, '0')}:${String(ctrl.minute).padStart(
              2,
              '0',
            )}:${String(ctrl.second).padStart(2, '0')}`,
            hour: ctrl.hour,
            minute: ctrl.minute,
            second: ctrl.second,
            peakValleyType: ctrl.peakValleyType,
            ctrlType: ctrl.ctrlType,
            targetPower: ctrl.targetPower,
            socUpperLimit: ctrl.socUpperLimit,
            socLowLimit: ctrl.socLowLimit,
          })),
        };

        // 调用更新接口
        const res = await strategySchemeControllerImplUpdateTimeScheme(
          { scheme_id: currentEditingTabKey.toString() },
          params,
        );

        if (res.success) {
          // 更新本地状态
          const updatedSchemes = tempSchemes.map((scheme) =>
            scheme.id === currentEditingTabKey ? { ...scheme, schemeName: values.tabName } : scheme,
          );

          // 更新 tempSchemes
          updateTempSchemes(updatedSchemes);

          // 更新 strategyItems
          const updatedStrategyItems = strategyItems.map((item) =>
            item.key === currentEditingTabKey.toString()
              ? { ...item, label: values.tabName }
              : item,
          );
          setStrategyItems(updatedStrategyItems);

          message.success(
            intl.formatMessage({ id: 'strategyAction.error.strategyNameUpdateSuccess' }),
          );
          setEditTabNameModalVisible(false);
          setCurrentEditingTabName('');
          setCurrentEditingTabKey(null);
          return true;
        } else {
          message.error(
            res.message ||
              intl.formatMessage({ id: 'strategyAction.error.updateStrategyNameFailed' }),
          );
          return false;
        }
      } catch (error) {
        console.error('更新策略名称失败:', error);
        message.error(intl.formatMessage({ id: 'strategyAction.error.updateStrategyNameFailed' }));
        return false;
      }
    };

    //  Tabs 组件的 items 属性中，每个 item 添加一个 tab 属性
    const tabRender = (originNode: React.ReactNode, info: { key: string }) => {
      const tabKey = Number(info.key);

      // 如果是 React.ReactElement 类，我们可以隆并添加编辑图标
      if (React.isValidElement(originNode) && !readOnly) {
        return React.cloneElement(originNode, {
          ...originNode.props,
          children: (
            <div
              style={{
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'space-between',
                width: '100%',
              }}
            >
              {originNode.props.children}
              <EditOutlined
                style={{
                  color: '#1890ff',
                  cursor: 'pointer',
                  marginLeft: 8,
                }}
                onClick={(e) => {
                  e.stopPropagation();
                  const currentScheme = tempSchemes.find((scheme) => scheme.id === tabKey);
                  if (currentScheme) {
                    // 关键改：直使用当前 scheme 的名称
                    setCurrentEditingTabName(currentScheme.schemeName);
                    setCurrentEditingTabKey(tabKey);
                    setEditTabNameModalVisible(true);
                  }
                }}
              />
            </div>
          ),
        });
      }

      return originNode;
    };

    useEffect(() => {
      const initializeData = async () => {
        try {
          const schemes = await getTimeSchemes();

          // 如果有方案，自动选择第一个
          if (schemes && schemes.length > 0) {
            setActiveStrategyTab(schemes[0].id);
          } else {
            message.info(
              intl.formatMessage({ id: 'strategyAction.error.noTimeStrategyPlanPleaseAdd' }),
            );
          }
        } catch (error) {
          console.error('初始化数据失败:', error);
          message.error(intl.formatMessage({ id: 'strategyAction.error.loadStrategyPlanFailed' }));
        }
      };

      initializeData();
    }, []);

    return (
      <div>
        <div style={{ marginBottom: 20 }} className={styles.strategyConfig}>
          <h3>{intl.formatMessage({ id: 'strategyAction.settings.strategyConfig' })}</h3>
          <ProFormRadio.Group
            name="executionMode"
            label={intl.formatMessage({ id: 'strategyAction.settings.executionMode' })}
            options={getExecutionModeOptions(intl)}
            fieldProps={{
              value: executionMode,
              onChange: readOnly
                ? undefined
                : (e: RadioChangeEvent) => setExecutionMode(e.target.value as 'date' | 'week'),
              disabled: readOnly,
            }}
          />
          <div style={{ marginTop: 0 }}>
            <span>{intl.formatMessage({ id: 'strategyAction.settings.executionTime' })}：</span>
            {(executionMode === 'date' ? tagsData : weekTagsData).map((tag) => (
              <Tag.CheckableTag
                key={tag}
                checked={
                  executionMode === 'date'
                    ? selectedMonths.includes(tag)
                    : selectedWeek.includes(tag)
                }
                onChange={(checked) => handleTagChange(tag, checked)}
                className={`${styles.tag}`}
              >
                {tag}
              </Tag.CheckableTag>
            ))}
          </div>
        </div>
        <div className={styles.strategyConfig}>
          <h3>{intl.formatMessage({ id: 'strategyAction.timeStrategyPlan' })}</h3>
          <ConfigProvider
            theme={{
              components: {
                Tabs: {
                  cardHeight: 20,
                  cardPadding: '0',
                },
              },
            }}
          >
            <Tabs
              activeKey={String(activeStrategyTab)}
              items={strategyItems}
              onChange={(key) => {
                console.log('Tab changed to:', key);
                setActiveStrategyTab(Number(key));
              }}
              type="editable-card"
              hideAdd={true}
              size="small"
              onEdit={handleEdit}
              tabBarExtraContent={
                showActions ? (
                  <Space>
                    <HandleBtn handleType="add" onClick={() => setAddStrategyModalVisible(true)}>
                      {intl.formatMessage({ id: 'strategyAction.error.addStrategyPlan' })}
                    </HandleBtn>
                    <HandleBtn handleType="add" onClick={() => setAddTimeSlotModalVisible(true)}>
                      {intl.formatMessage({ id: 'strategyAction.error.addTimeSlot' })}
                    </HandleBtn>
                  </Space>
                ) : null
              }
              renderTabBar={(props, DefaultTabBar) => (
                <DefaultTabBar {...props}>
                  {(node) => tabRender(node, { key: node.key.toString() })}
                </DefaultTabBar>
              )}
            />
          </ConfigProvider>
        </div>
        <ModalForm
          key={formKey}
          title={`${
            executionMode === 'week' ? `${weekTagsData[currentEditingWeekIndex]}` : currentMonth
          }${intl.formatMessage({ id: 'strategyAction.settings.strategyConfig' })}`}
          visible={modalVisible}
          onVisibleChange={handleModalVisibleChange}
          onFinish={handleModalSubmit}
          submitter={{
            render: (props, dom) => <Space style={{ float: 'right' }}>{dom}</Space>,
          }}
          modalProps={{
            destroyOnClose: true,
          }}
          width={executionMode === 'week' ? 420 : undefined}
          style={{ marginRight: 0 }}
        >
          {renderModalContent()}
        </ModalForm>
        <ModalForm
          title={intl.formatMessage({ id: 'strategyAction.error.addTimeStrategyPlan' })}
          open={addStrategyModalVisible}
          key={Date.now()}
          onOpenChange={setAddStrategyModalVisible}
          onFinish={async (values: { strategyName: string }) => {
            // 验方案名称
            if (!values.strategyName?.trim()) {
              message.error(
                intl.formatMessage({ id: 'strategyAction.error.strategyNameCannotBeEmpty' }),
              );
              return false;
            }
            await handleAddNewStrategy(values);
            return true;
          }}
          width={420}
        >
          <ProFormText
            name="strategyName"
            label={intl.formatMessage({ id: 'strategyAction.timeSettings.strategyName' })}
            rules={getStrategyNameRules(intl)}
          />
        </ModalForm>
        <ModalForm
          title={
            isEditMode
              ? intl.formatMessage({ id: 'strategyAction.timeSettings.editTimeSlot' })
              : intl.formatMessage({ id: 'strategyAction.timeSettings.addTimeSlot' })
          }
          visible={addTimeSlotModalVisible}
          form={form}
          style={{ marginRight: 0 }}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setAddTimeSlotModalVisible(false);
              setEditingTimeCtrl(null);
              setIsEditMode(false);
              form.resetFields();
            },
          }}
          onVisibleChange={(visible) => {
            if (!visible) {
              setEditingTimeCtrl(null);
              setIsEditMode(false);
              form.resetFields();
            }
          }}
          onFinish={handleAddTimeSlot}
        >
          <ProForm.Group>
            <ProFormSelect
              name="chargeType"
              label={intl.formatMessage({
                id: 'strategyAction.chargeDischargeStrategy.chargeDischargeType',
              })}
              width="sm"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.chargeDischargeStrategy.pleaseSelectChargeDischargeType',
                  }),
                },
              ]}
              options={getChargeTypeOptions(intl)}
              colProps={{
                span: 12,
              }}
              labelCol={isEnglish ? { span: 12 } : { span: 8 }}
            />
            <ProFormSelect
              name="timeType"
              label={intl.formatMessage({ id: 'strategyAction.periodType' })}
              width="sm"
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.timeSettings.pleaseSelectPeriodType',
                  }),
                },
              ]}
              options={getTimeTypeOptions(intl)}
              colProps={{
                span: 12,
              }}
              labelCol={isEnglish ? { span: 12 } : { span: 8 }}
            />
          </ProForm.Group>

          <ProForm.Group>
            <ProFormTimePicker
              name="startTime"
              label={intl.formatMessage({ id: 'strategyAction.timeSettings.startTime' })}
              width={isEnglish ? 'md' : 'sm'}
              fieldProps={{
                format: 'HH:mm:ss',
                onChange: (time) => {
                  if (!time) return;

                  const timeStr = time.format('HH:mm:ss');
                  const currentScheme = tempSchemes.find(
                    (scheme) => scheme.id === activeStrategyTab,
                  );

                  if (!currentScheme) return;

                  // 验证时间是否重复
                  const timeExists = currentScheme.timeCtrls.some((ctrl) => {
                    // 编辑模式下排除当前正在编辑的时间
                    if (isEditMode && ctrl.timeKey === editingTimeCtrl?.originalTimeKey) {
                      return false;
                    }
                    return ctrl.startTime === timeStr;
                  });

                  if (timeExists) {
                    message.error(
                      intl.formatMessage({ id: 'strategyAction.timeSettings.timeAlreadyExists' }),
                    );
                    // 清空选择的时间
                    form.setFieldValue('startTime', null);
                  }
                },
              }}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.timeSettings.pleaseSelectStartTime',
                  }),
                },
              ]}
              colProps={{
                span: 12,
              }}
              labelCol={isEnglish ? { span: 12 } : { span: 8 }}
            />
          </ProForm.Group>

          <ProForm.Group>
            <ProFormDigit
              name="socUpper"
              label={intl.formatMessage({ id: 'strategyAction.timeSettings.SOCUpper' })}
              width={isEnglish ? 'md' : 'sm'}
              fieldProps={{ addonAfter: '%' }}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.timeSettings.pleaseEnterSOCUpper',
                  }),
                },
                {
                  type: 'number',
                  min: 1,
                  max: 100,
                  message: intl.formatMessage({ id: 'strategyAction.timeSettings.SOCUpperRange' }),
                },
                // 新增自定义校验规则
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    const socLower = getFieldValue('socLower');
                    if (value <= socLower) {
                      return Promise.reject(
                        new Error(
                          intl.formatMessage({
                            id: 'strategyAction.timeSettings.SOCUpperMustBeGreaterThanSOCLower',
                          }),
                        ),
                      );
                    }
                    return Promise.resolve();
                  },
                }),
              ]}
              colProps={{
                span: 12,
              }}
              labelCol={isEnglish ? { span: 12 } : { span: 8 }}
            />
            <ProFormDigit
              name="socLower"
              label={intl.formatMessage({ id: 'strategyAction.timeSettings.SOCLower' })}
              width={isEnglish ? 'md' : 'sm'}
              fieldProps={{ addonAfter: '%' }}
              rules={[
                {
                  required: true,
                  message: intl.formatMessage({
                    id: 'strategyAction.timeSettings.pleaseEnterSOCLower',
                  }),
                },
                {
                  type: 'number',
                  min: 0,
                  max: 100,
                  message: intl.formatMessage({ id: 'strategyAction.timeSettings.SOCLowerRange' }),
                },
                // 新增自定义校验规
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    const socUpper = getFieldValue('socUpper');
                    if (socUpper !== undefined && value >= socUpper) {
                      return Promise.reject(
                        new Error(
                          intl.formatMessage({
                            id: 'strategyAction.timeSettings.SOCLowerMustBeLessThanSOCUpper',
                          }),
                        ),
                      );
                    }
                    return Promise.resolve();
                  },
                }),
              ]}
              colProps={{
                span: 12,
              }}
              labelCol={isEnglish ? { span: 12 } : { span: 8 }}
            />
          </ProForm.Group>

          <ProFormDigit
            name="targetPower"
            label={intl.formatMessage({ id: 'strategyAction.targetPower' })}
            width={isEnglish ? 'md' : 'sm'}
            fieldProps={{ addonAfter: 'kW' }}
            rules={[
              { required: true, message: intl.formatMessage({ id: 'strategyAction.pleaseEnter' }) },
            ]}
            colProps={{
              span: 12,
            }}
            labelCol={isEnglish ? { span: 12 } : { span: 8 }}
          />
        </ModalForm>
        <ModalForm
          key={currentEditingTabKey}
          title={intl.formatMessage({ id: 'strategyAction.timeSettings.editStrategyPlanName' })}
          open={editTabNameModalVisible}
          onOpenChange={(visible) => {
            setEditTabNameModalVisible(visible);
            if (!visible) {
              // 关闭窗时重置状态
              setCurrentEditingTabName('');
              setCurrentEditingTabKey(null);
            }
          }}
          onFinish={handleEditTabName}
          width={420}
        >
          <ProFormText
            name="tabName"
            label={intl.formatMessage({ id: 'strategyAction.timeSettings.strategyName' })}
            initialValue={currentEditingTabName}
            rules={[
              {
                required: true,
                message: intl.formatMessage({
                  id: 'strategyAction.timeSettings.pleaseEnterStrategyName',
                }),
              },
              {
                min: 2,
                message: intl.formatMessage({
                  id: 'strategyAction.timeSettings.strategyNameMustBeAtLeast2Characters',
                }),
              },
              {
                max: 50,
                message: intl.formatMessage({
                  id: 'strategyAction.timeSettings.strategyNameMustBeLessThan50Characters',
                }),
              },
              {
                pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_-]+$/,
                message: intl.formatMessage({
                  id: 'strategyAction.timeSettings.strategyNameCanOnlyContainChineseEnglishNumbersUnderscoresAndHyphens',
                }),
              },
            ]}
          />
        </ModalForm>
      </div>
    );
  },
);

export default TimeSettings;
